from datetime import datetime, timedelta
from sqlalchemy import create_engine, Column, Integer, String, DateTime, Float
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

Base = declarative_base()

class ParkingRecord(Base):
    __tablename__ = 'parking_records'
    
    id = Column(Integer, primary_key=True)
    license_plate = Column(String(20), nullable=False)
    vehicle_type = Column(String(20), default='小型车')
    entry_time = Column(DateTime, nullable=False)
    exit_time = Column(DateTime)
    parking_fee = Column(Float, default=0.0)
    is_paid = Column(Integer, default=0)
    created_at = Column(DateTime, default=datetime.now)

class ParkingConfig(Base):
    __tablename__ = 'parking_config'
    
    id = Column(Integer, primary_key=True)
    total_spaces = Column(Integer, default=100)
    first_hour_fee = Column(Float, default=5.0)
    additional_hour_fee = Column(Float, default=2.0)

class Admin(Base):
    __tablename__ = 'admins'
    
    id = Column(Integer, primary_key=True)
    username = Column(String(50), unique=True, nullable=False)
    password = Column(String(100), nullable=False)

class Database:
    def __init__(self, db_url='sqlite:///parking.db'):
        self.engine = create_engine(db_url)
        Base.metadata.create_all(self.engine)
        Session = sessionmaker(bind=self.engine)
        self.session = Session()
        
        # 初始化配置
        if not self.session.query(ParkingConfig).first():
            config = ParkingConfig(total_spaces=100, first_hour_fee=5.0, additional_hour_fee=2.0)
            self.session.add(config)
            self.session.commit()
            
        # 初始化管理员
        if not self.session.query(Admin).first():
            admin = Admin(username='admin', password='admin123')
            self.session.add(admin)
            self.session.commit()
    
    def get_config(self):
        return self.session.query(ParkingConfig).first()
    
    def update_config(self, total_spaces, first_hour_fee, additional_hour_fee):
        config = self.get_config()
        config.total_spaces = total_spaces
        config.first_hour_fee = first_hour_fee
        config.additional_hour_fee = additional_hour_fee
        self.session.commit()
    
    def get_occupied_spaces(self):
        return self.session.query(ParkingRecord).filter(
            ParkingRecord.exit_time.is_(None)
        ).count()
    
    def add_parking_record(self, license_plate, vehicle_type='小型车'):
        record = ParkingRecord(
            license_plate=license_plate,
            vehicle_type=vehicle_type,
            entry_time=datetime.now()
        )
        self.session.add(record)
        self.session.commit()
        return record
    
    def get_parking_record(self, license_plate):
        return self.session.query(ParkingRecord).filter(
            ParkingRecord.license_plate == license_plate,
            ParkingRecord.exit_time.is_(None)
        ).first()
    
    def calculate_fee(self, entry_time, exit_time=None):
        if exit_time is None:
            exit_time = datetime.now()
        
        duration = exit_time - entry_time
        hours = duration.total_seconds() / 3600
        
        config = self.get_config()
        
        if hours <= 1:
            return config.first_hour_fee
        else:
            return config.first_hour_fee + (int(hours) * config.additional_hour_fee)
    
    def exit_parking(self, license_plate):
        record = self.get_parking_record(license_plate)
        if record:
            record.exit_time = datetime.now()
            record.parking_fee = self.calculate_fee(record.entry_time, record.exit_time)
            self.session.commit()
            return record
        return None
    
    def pay_parking_fee(self, license_plate):
        record = self.exit_parking(license_plate)
        if record:
            record.is_paid = 1
            self.session.commit()
            return record
        return None
    
    def get_today_records(self):
        today = datetime.now().date()
        return self.session.query(ParkingRecord).filter(
            ParkingRecord.created_at >= today
        ).all()
    
    def get_all_records(self):
        return self.session.query(ParkingRecord).order_by(ParkingRecord.created_at.desc()).all()
    
    def get_today_income(self):
        today = datetime.now().date()
        records = self.session.query(ParkingRecord).filter(
            ParkingRecord.exit_time.isnot(None),
            ParkingRecord.is_paid == 1,
            ParkingRecord.created_at >= today
        ).all()
        return sum(record.parking_fee for record in records)
    
    def admin_login(self, username, password):
        admin = self.session.query(Admin).filter(
            Admin.username == username,
            Admin.password == password
        ).first()
        return admin is not None
    
    def close(self):
        self.session.close()
